package com.example.weather

import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.example.weather.Other.NetworkStateBroadcast
import com.example.weather.city_manager.CityManagerActivity
import com.example.weather.data.City
import com.example.weather.data.CityDao
import com.example.weather.data.WeatherDatabase
import com.example.weather.databinding.ActivityMainBinding
import java.lang.Exception
import java.util.ArrayList
import androidx.lifecycle.ViewModelProvider.NewInstanceFactory

// 导入所需的库和类

/**
 * @author Y7993
 */
// 主活动类，负责天气应用的主界面逻辑
class MainActivity : AppCompatActivity(), View.OnClickListener {
    var fragmentList: MutableList<Fragment?> = ArrayList<Fragment?>()

    //要显示的城市集合
    var cityList: MutableList<String?> = ArrayList<String?>()

    //表示ViewPager页数指示器显示集合
    var imgList: MutableList<ImageView?> = ArrayList<ImageView?>()

    //自定义适配器
    private var adapter: CityFragmentPagerAdapter? = null
    var hotCitys: Array<String?> = arrayOf<String?>("北京", "太原")

    //以下为修改架构组件的内容
    private var binding: ActivityMainBinding? = null
    private var cityDao: CityDao? = null

    // 创建活动的生命周期方法
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (!cityList.isEmpty()) {
            cityList.clear() //清空原本数据源
        }
        val weatherDatabase = WeatherDatabase.getDatabase(this)
        cityDao = weatherDatabase.getCityDao()
        cityList = getData()
        try {
            val intent = getIntent()
            val city = intent.getStringExtra("city")
            if (!cityList.contains(city) && !TextUtils.isEmpty(city)) {
                cityList.add(city)
                val cc = City(city)
                cityDao!!.insetCity(cc)
            }
        } catch (_: Exception) {
            Log.i("animee", "error")
        }
        //初始化viewpager页面
        initPager()
        //以下为修改架构组件的内容
        binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        val mainVM = ViewModelProvider(this, NewInstanceFactory()).get<MainVM>(MainVM::class.java)
        //初始化数据
        mainVM.setCitylist(cityList)
        //添加点击事件
        binding!!.mainIvAdd.setOnClickListener(this)
        binding!!.mainIvMore.setOnClickListener(this)
        //创建适配器
        adapter = CityFragmentPagerAdapter(supportFragmentManager, fragmentList)
        binding!!.mainVp.adapter = adapter
        //创建小圆点指示器
        initPoint()
        //设置最后一个城市信息
        binding!!.mainVp.currentItem = fragmentList.size - 1
        setPagerListener()
        setBackGround()
        binding!!.setCityData(mainVM)
        binding!!.lifecycleOwner = this
        registReceiver()
    }

    // 活动重启时的方法，重新加载城市数据
    override fun onRestart() {
        super.onRestart()
        cityList.clear() //清空原本数据源
        cityList = getData()
        fragmentList.clear()
        initPager()
        adapter!!.notifyDataSetChanged()
        imgList.clear()
        binding!!.mainLayoutPoint.removeAllViews() //将布局当中所有元素全部移除
        initPoint()
        binding!!.mainVp.currentItem = fragmentList.size - 1
    }

    // 获取城市数据的方法
    private fun getData(): MutableList<String?> {
        val cityList: MutableList<String?> = ArrayList<String?>()
        var cities = cityDao!!.findAll()
        cities?.let {
            if (it.isEmpty()) {
                for (tmp_name in hotCitys) {
                    cityDao!!.insetCity(City(tmp_name))
                    println("插入了城市$tmp_name\n")
                }
                cities = cityDao!!.findAll()
            }
        }
        if (cities != null) {
            for (c in cities) {
                c?.let { cityList.add(it.getName()) }
                println(c)
            }
        }
        return cityList
    }

    // 注册网络状态广播接收器
    fun registReceiver() {
        //广播
        val stateBroadcast = NetworkStateBroadcast()
        val filter = IntentFilter()
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        filter.priority = Int.Companion.MAX_VALUE
        registerReceiver(stateBroadcast, filter)
    }

    // 设置背景方法
    private fun setBackGround() {
        //轻量级的数据存储
        val pref = getSharedPreferences("bg_pref", MODE_PRIVATE)
        val bgNum = pref.getInt("bg", 2)
        when (bgNum) {
            0 -> binding!!.mainOutLayout.setBackgroundResource(R.mipmap.bg)
            1 -> binding!!.mainOutLayout.setBackgroundResource(R.mipmap.bg2)
            2 -> binding!!.mainOutLayout.setBackgroundResource(R.mipmap.bg3)
        }
    }

    // 设置ViewPager监听器的方法
    private fun setPagerListener() { //设置监听
        binding!!.mainVp.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                for (i in imgList.indices) {
                    imgList[i]!!.setImageResource(R.mipmap.a1)
                }
                imgList[position]!!.setImageResource(R.mipmap.a2)
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })
    }

    // 初始化小圆点指示器的方法
    private fun initPoint() { // 创建小圆点 ViewPager页面指示器的函数
        for (i in fragmentList.indices) {
            val pIv = ImageView(this)
            pIv.setImageResource(R.mipmap.a1)
            pIv.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            val lp = pIv.layoutParams as LinearLayout.LayoutParams
            lp.setMargins(0, 0, 20, 0)
            imgList.add(pIv)
            binding!!.mainLayoutPoint.addView(pIv)
        }
        imgList[imgList.size - 1]!!.setImageResource(R.mipmap.a2)
    }

    // 初始化ViewPager的方法，创建Fragment对象并添加到数据源中
    private fun initPager() { // 创建Fragment对象，添加到ViewPager数据源当中
        for (i in cityList.indices) {
            val cwFrag = CityWeatherFragment()
            val bundle = Bundle()
            bundle.putString("city", cityList[i])
            cwFrag.arguments = bundle
            fragmentList.add(cwFrag)
        }
    }

    // 点击事件的处理方法
    override fun onClick(view: View) {
        if (view.id == R.id.main_iv_add) {
            val intent_add = Intent(this, CityManagerActivity::class.java)
            startActivity(intent_add)
        } else if (view.id == R.id.main_iv_more) {
            val intent_more = Intent(this, MoreActivity::class.java)
            startActivity(intent_more)
        }
    }
}
